package controller;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import model.GroupManager;
import model.Student;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name").trim();
        String studentId = request.getParameter("studentId").trim();

        // 判断是否为管理员登录
        if ("admin".equals(name) && "admin".equals(studentId)) {
            HttpSession session = request.getSession();
            session.setAttribute("isAdmin", true);
            response.sendRedirect("AdminServlet");
            return;
        }

        GroupManager groupManager = (GroupManager) getServletContext().getAttribute("groupManager");

        if (groupManager.isValidStudent(name, studentId)) {
            if (groupManager.isStudentGrouped(studentId)) {
                // 已经分组
                HttpSession session = request.getSession();
                session.setAttribute("student", new Student(name, studentId));
                response.sendRedirect("GroupServlet");
            } else {
                // 进行分组
                Student student = new Student(name, studentId);
                groupManager.addStudentToGroup(student);
                HttpSession session = request.getSession();
                session.setAttribute("student", student);
                response.sendRedirect("GroupServlet");
            }
        } else {
            // 验证失败，返回登录页面
            request.setAttribute("error", "姓名或学号错误！");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}
